#include "cartui.h"
#include "constants.h"
#include "usermanager.h"
#include <QApplication>
#include <QUuid>

using namespace RestaurantSystem;

CustomerCartUI::CustomerCartUI(QWidget *parent)
    : QWidget(parent)
    , m_orderManager(nullptr)
    , m_menuManager(nullptr)
    , m_currentUserId(-1)
    , m_totalAmount(0.0)
{
    initializeUI();
}

CustomerCartUI::~CustomerCartUI()
{
    // Qt会自动清理子对象
}

void CustomerCartUI::setManagers(OrderManager *orderManager, MenuManager *menuManager)
{
    m_orderManager = orderManager;
    m_menuManager = menuManager;
}

void CustomerCartUI::setCurrentUserId(int userId)
{
    // 如果用户ID发生变化，清除购物车数据
    if (m_currentUserId != userId && m_currentUserId != -1) {
        clearCartForUserSwitch();
    }
    m_currentUserId = userId;
}

void CustomerCartUI::addItemToCart(const QString &menuItemId, int quantity)
{
    if (!m_menuManager || menuItemId.isEmpty() || quantity <= 0) {
        return;
    }

    // 获取菜品信息
    auto menuItems = m_menuManager->getAllMenuItems();
    MenuItem targetItem;
    bool found = false;
    
    for (const auto &item : menuItems) {
        if (item.id == menuItemId) {
            targetItem = item;
            found = true;
            break;
        }
    }
    
    if (!found) {
        QMessageBox::warning(this, "错误", QString("找不到菜品: %1").arg(menuItemId));
        return;
    }
    
    // 检查库存是否充足
    if (targetItem.stock <= 0) {
        QMessageBox::warning(this, "库存不足", QString("菜品 \"%1\" 暂时缺货").arg(targetItem.name));
        return;
    }
    
    // 检查购物车中是否已存在该商品
    bool itemExists = false;
    int actuallyAdded = 0;
    
    for (auto &cartItem : m_cartItems) {
        if (cartItem.menuItemId == menuItemId) {
            int currentQuantity = cartItem.quantity;
            int requestedQuantity = quantity;
            int maxPossible = targetItem.stock - currentQuantity;
            
            if (maxPossible <= 0) {
                // 已经达到库存上限，无法再添加
                QMessageBox::information(this, "库存已满", 
                    QString("菜品 \"%1\" 已达到库存上限！\n当前购物车数量：%2\n最大库存：%3")
                    .arg(targetItem.name)
                    .arg(currentQuantity)
                    .arg(targetItem.stock));
                return;
            }
            
            // 计算实际能添加的数量
            actuallyAdded = qMin(requestedQuantity, maxPossible);
            cartItem.quantity = currentQuantity + actuallyAdded;
            cartItem.availableStock = targetItem.stock;  // 更新库存信息
            cartItem.calculateSubtotal();
            
            // 如果实际添加数量少于请求数量，提示用户
            if (actuallyAdded < requestedQuantity) {
                QMessageBox::information(this, "部分添加成功", 
                    QString("菜品 \"%1\" 库存有限！\n请求添加：%2个\n实际添加：%3个\n当前购物车总数：%4个\n最大库存：%5个")
                    .arg(targetItem.name)
                    .arg(requestedQuantity)
                    .arg(actuallyAdded)
                    .arg(cartItem.quantity)
                    .arg(targetItem.stock));
            }
            // 正常添加成功时不显示弹窗，通过界面更新让用户知道操作成功
            
            itemExists = true;
            break;
        }
    }
    
    // 如果不存在，添加新项
    if (!itemExists) {
        // 检查库存是否为0（这种情况应该在前面已经处理，但为了安全再次检查）
        if (targetItem.stock <= 0) {
            // 这种情况理论上不应该发生，因为前面已经检查过了
            QMessageBox::warning(this, "库存不足", QString("菜品 \"%1\" 暂时缺货").arg(targetItem.name));
            return;
        }
        
        // 计算实际能添加的数量
        actuallyAdded = qMin(quantity, targetItem.stock);
        
        // 确保添加数量大于0
        if (actuallyAdded <= 0) {
            QMessageBox::information(this, "无法添加", 
                QString("菜品 \"%1\" 无法添加到购物车").arg(targetItem.name));
            return;
        }
        
        CartItem newItem(menuItemId, targetItem.name, targetItem.price, actuallyAdded, targetItem.stock);
        m_cartItems.append(newItem);
        
        // 如果实际添加数量少于请求数量，提示用户
        if (actuallyAdded < quantity) {
            QMessageBox::information(this, "部分添加成功", 
                QString("菜品 \"%1\" 库存有限！\n请求添加：%2个\n实际添加：%3个\n最大库存：%4个")
                .arg(targetItem.name)
                .arg(quantity)
                .arg(actuallyAdded)
                .arg(targetItem.stock));
        }
        // 正常添加成功时不显示弹窗，通过界面更新让用户知道操作成功
    }
    
    // 更新界面
    updateCartDisplay();
    calculateTotals();
    
    // 发送信号
    emit cartChanged(m_cartItems.size(), m_totalAmount);
}

void CustomerCartUI::clearCart()
{
    m_cartItems.clear();
    updateCartDisplay();
    calculateTotals();
    emit cartChanged(0, 0.0);
}

void CustomerCartUI::clearCartForUserSwitch()
{
    // 静默清除购物车数据，用于用户切换时
    m_cartItems.clear();
    updateCartDisplay();
    calculateTotals();
    emit cartChanged(0, 0.0);
}

void CustomerCartUI::handleCheckout()
{
    if (m_cartItems.isEmpty()) {
        QMessageBox::warning(this, "提示", "购物车为空，无法下单");
        return;
    }
    
    if (!m_orderManager) {
        QMessageBox::warning(this, "错误", "订单管理器未初始化");
        return;
    }
    
    // 确认下单
    int ret = QMessageBox::question(this, "确认下单", 
                                   QString("确定要提交订单吗？\n总金额: ¥%1").arg(m_totalAmount, 0, 'f', 2),
                                   QMessageBox::Yes | QMessageBox::No);
    
    if (ret != QMessageBox::Yes) {
        return;
    }
    
    // 创建订单项列表
    QList<OrderItem> orderItems;
    for (const auto &cartItem : m_cartItems) {
        OrderItem orderItem(cartItem.menuItemId, cartItem.menuItemName, 
                          cartItem.price, cartItem.quantity);
        orderItems.append(orderItem);
    }
    
    // 创建订单请求
    // 直接从UserManager获取真实的用户ID字符串
    UserManager &userManager = UserManager::instance();
    QString customerId = userManager.getCurrentUserId();
    if (customerId.isEmpty()) {
        // 如果无法获取用户ID，使用备用方案
        customerId = QString::number(m_currentUserId);
    }
    OrderCreateRequest request(customerId, orderItems, "现金支付", "");
    
    auto result = m_orderManager->createOrder(request);
    if (result.first == OrderOperationResult::SUCCESS) {
        QString orderId = result.second;
        
        // 下单成功，清空购物车
        clearCart();
        
        // 发送成功信号
        emit orderSubmitted(orderId);
        
        // 显示成功消息
        QMessageBox::information(this, "下单成功", 
                               QString("订单已提交成功！\n订单号: %1").arg(orderId));
    } else {
        QMessageBox::critical(this, "下单失败", "订单提交失败，请重试");
    }
}

void CustomerCartUI::handleBackToMenu()
{
    emit backToMenuRequested();
}

void CustomerCartUI::handleClearCart()
{
    if (m_cartItems.isEmpty()) {
        return;
    }
    
    int ret = QMessageBox::question(this, "确认清空", 
                                   "确定要清空购物车吗？此操作不可撤销。",
                                   QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        clearCart();
    }
}

void CustomerCartUI::initializeUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(15);
    
    // 标题和返回按钮
    QHBoxLayout *headerLayout = new QHBoxLayout();
    m_titleLabel = new QLabel("购物车", this);
    m_titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color: #2c3e50;");
    
    m_backButton = new QPushButton("← 返回菜单", this);
    m_backButton->setStyleSheet("background-color: #6c757d; color: white; border: none; padding: 8px 16px; border-radius: 4px;");
    connect(m_backButton, &QPushButton::clicked, this, &CustomerCartUI::handleBackToMenu);
    
    headerLayout->addWidget(m_titleLabel);
    headerLayout->addStretch();
    headerLayout->addWidget(m_backButton);
    
    m_mainLayout->addLayout(headerLayout);
    
    // 购物车表格
    m_cartTable = new QTableWidget(this);
    m_cartTable->setColumnCount(6);
    m_cartTable->setHorizontalHeaderLabels({"菜品名称", "单价", "数量", "库存", "小计", "操作"});
    m_cartTable->horizontalHeader()->setStretchLastSection(true);
    m_cartTable->setAlternatingRowColors(true);
    m_cartTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_cartTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_cartTable->setStyleSheet("QTableWidget { border: 1px solid #dee2e6; border-radius: 4px; background-color: white; }");
    
    m_mainLayout->addWidget(m_cartTable, 1);
    
    // 总计区域
    m_totalLabel = new QLabel("总计: ¥0.00", this);
    m_totalLabel->setStyleSheet("font-size: 20px; font-weight: bold; color: #dc3545; text-align: right; padding: 10px;");
    m_totalLabel->setAlignment(Qt::AlignRight);
    
    m_mainLayout->addWidget(m_totalLabel);
    
    // 操作按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    
    m_clearButton = new QPushButton("清空购物车", this);
    m_clearButton->setStyleSheet("background-color: #dc3545; color: white; border: none; padding: 10px 20px; border-radius: 4px; font-size: 16px;");
    connect(m_clearButton, &QPushButton::clicked, this, &CustomerCartUI::handleClearCart);
    
    m_checkoutButton = new QPushButton("立即下单", this);
    m_checkoutButton->setStyleSheet("background-color: #28a745; color: white; border: none; padding: 10px 30px; border-radius: 4px; font-size: 18px; font-weight: bold;");
    connect(m_checkoutButton, &QPushButton::clicked, this, &CustomerCartUI::handleCheckout);
    
    buttonLayout->addWidget(m_clearButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_checkoutButton);
    
    m_mainLayout->addLayout(buttonLayout);
    
    // 初始状态
    updateCartDisplay();
    calculateTotals();
}

void CustomerCartUI::updateCartDisplay()
{
    m_cartTable->setRowCount(m_cartItems.size());
    
    for (int i = 0; i < m_cartItems.size(); ++i) {
        const auto &item = m_cartItems[i];
        
        // 菜品名称
        m_cartTable->setItem(i, 0, new QTableWidgetItem(item.menuItemName));
        
        // 单价
        m_cartTable->setItem(i, 1, new QTableWidgetItem(QString("¥%1").arg(item.price, 0, 'f', 2)));
        
        // 数量 - 使用+/-按钮和数量显示
        QWidget *quantityWidget = new QWidget();
        QHBoxLayout *quantityLayout = new QHBoxLayout(quantityWidget);
        quantityLayout->setContentsMargins(5, 2, 5, 2);
        quantityLayout->setSpacing(5);
        
        QPushButton *decreaseBtn = new QPushButton("-", quantityWidget);
        decreaseBtn->setFixedSize(25, 25);
        decreaseBtn->setStyleSheet("QPushButton { background-color: #dc3545; color: white; border: none; border-radius: 12px; font-weight: bold; }");
        decreaseBtn->setToolTip("减少数量");
        
        // 数量显示标签
        QLabel *quantityLabel = new QLabel(QString::number(item.quantity), quantityWidget);
        quantityLabel->setFixedWidth(40);
        quantityLabel->setAlignment(Qt::AlignCenter);
        quantityLabel->setStyleSheet("QLabel { font-size: 14px; font-weight: bold; color: #2c3e50; background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 3px; padding: 2px; }");
        
        // 根据库存情况给数量标签添加提示
        if (item.quantity >= item.availableStock) {
            quantityLabel->setToolTip(QString("已达到最大库存限制 (%1)").arg(item.availableStock));
        } else {
            quantityLabel->setToolTip(QString("当前数量：%1，库存：%2件").arg(item.quantity).arg(item.availableStock));
        }
        
        QPushButton *increaseBtn = new QPushButton("+", quantityWidget);
        increaseBtn->setFixedSize(25, 25);
        
        // 根据库存情况设置增加按钮的状态和样式
        if (item.quantity >= item.availableStock) {
            increaseBtn->setEnabled(false);
            increaseBtn->setStyleSheet("QPushButton { background-color: #6c757d; color: white; border: none; border-radius: 12px; font-weight: bold; }");
            increaseBtn->setToolTip("已达到最大库存限制");
        } else {
            increaseBtn->setEnabled(true);
            increaseBtn->setStyleSheet("QPushButton { background-color: #28a745; color: white; border: none; border-radius: 12px; font-weight: bold; }");
            increaseBtn->setToolTip(QString("增加数量，库存还有%1件").arg(item.availableStock - item.quantity));
        }
        
        // 连接信号 - 减量按钮：数量>1时减量，数量=1时移除
        connect(decreaseBtn, &QPushButton::clicked, [this, i]() {
            if (i >= m_cartItems.size()) return; // 边界检查
            
            if (m_cartItems[i].quantity > 1) {
                // 减量逻辑：数量大于1时，减少数量
                m_cartItems[i].quantity--;
                m_cartItems[i].calculateSubtotal();
                updateCartDisplay();
                calculateTotals();
                emit cartChanged(m_cartItems.size(), m_totalAmount);
            } else if (m_cartItems[i].quantity == 1) {
                // 移除确认逻辑：数量等于1时，询问是否移除菜品
                int ret = QMessageBox::question(this, "确认移除", 
                    QString("确定要从购物车中移除 \"%1\" 吗？").arg(m_cartItems[i].menuItemName),
                    QMessageBox::Yes | QMessageBox::No);
                if (ret == QMessageBox::Yes) {
                    m_cartItems.removeAt(i);
                    updateCartDisplay();
                    calculateTotals();
                    emit cartChanged(m_cartItems.size(), m_totalAmount);
                }
                // 如果用户选择No，则不执行任何操作，菜品保持在购物车中
            }
        });
        
        connect(increaseBtn, &QPushButton::clicked, [this, i]() {
            if (i < m_cartItems.size()) {
                if (m_cartItems[i].canIncreaseQuantity()) {
                    m_cartItems[i].quantity++;
                    m_cartItems[i].calculateSubtotal();
                    updateCartDisplay();
                    calculateTotals();
                    emit cartChanged(m_cartItems.size(), m_totalAmount);
                } else {
                    QMessageBox::information(this, "库存限制", 
                        QString("菜品 \"%1\" 已达到最大库存限制 (%2件)")
                        .arg(m_cartItems[i].menuItemName)
                        .arg(m_cartItems[i].availableStock));
                }
            }
        });
        
        quantityLayout->addWidget(decreaseBtn);
        quantityLayout->addWidget(quantityLabel);
        quantityLayout->addWidget(increaseBtn);
        
        m_cartTable->setCellWidget(i, 2, quantityWidget);
        
        // 库存信息
        QTableWidgetItem *stockItem = new QTableWidgetItem(QString("%1件").arg(item.availableStock));
        if (item.quantity >= item.availableStock) {
            // 库存不足时用红色显示
            stockItem->setForeground(QBrush(QColor("#dc3545")));
            stockItem->setToolTip("库存不足");
        } else if (item.availableStock - item.quantity <= 3) {
            // 库存紧张时用橙色显示
            stockItem->setForeground(QBrush(QColor("#fd7e14")));
            stockItem->setToolTip("库存紧张");
        } else {
            // 库存充足时用绿色显示
            stockItem->setForeground(QBrush(QColor("#28a745")));
            stockItem->setToolTip("库存充足");
        }
        stockItem->setTextAlignment(Qt::AlignCenter);
        m_cartTable->setItem(i, 3, stockItem);
        
        // 小计
        m_cartTable->setItem(i, 4, new QTableWidgetItem(QString("¥%1").arg(item.subtotal, 0, 'f', 2)));
        
        // 操作按钮 - 移除商品
        QWidget *actionWidget = new QWidget();
        QHBoxLayout *actionLayout = new QHBoxLayout(actionWidget);
        actionLayout->setContentsMargins(5, 2, 5, 2);
        actionLayout->setAlignment(Qt::AlignCenter);
        
        QPushButton *removeBtn = new QPushButton("移除", actionWidget);
        removeBtn->setStyleSheet("QPushButton { background-color: #fd7e14; color: white; border: none; padding: 4px 8px; border-radius: 3px; font-size: 12px; }");
        removeBtn->setProperty("row", i);
        
        connect(removeBtn, &QPushButton::clicked, [this, i]() {
            if (i < m_cartItems.size()) {
                int ret = QMessageBox::question(this, "确认移除", 
                                              QString("确定要移除 \"%1\" 吗？").arg(m_cartItems[i].menuItemName),
                                              QMessageBox::Yes | QMessageBox::No);
                if (ret == QMessageBox::Yes) {
                    m_cartItems.removeAt(i);
                    updateCartDisplay();
                    calculateTotals();
                    emit cartChanged(m_cartItems.size(), m_totalAmount);
                }
            }
        });
        
        actionLayout->addWidget(removeBtn);
        m_cartTable->setCellWidget(i, 5, actionWidget);
    }
    
    // 设置列宽（适配1024x600屏幕）
    m_cartTable->setColumnWidth(0, 160);  // 菜品名称
    m_cartTable->setColumnWidth(1, 65);   // 单价
    m_cartTable->setColumnWidth(2, 100);  // 数量控件
    m_cartTable->setColumnWidth(3, 55);   // 库存
    m_cartTable->setColumnWidth(4, 65);   // 小计
    m_cartTable->setColumnWidth(5, 65);   // 操作
    
    // 更新按钮状态
    bool hasItems = !m_cartItems.isEmpty();
    m_clearButton->setEnabled(hasItems);
    m_checkoutButton->setEnabled(hasItems);
}

void CustomerCartUI::calculateTotals()
{
    m_totalAmount = 0.0;
    
    for (const auto &item : m_cartItems) {
        m_totalAmount += item.subtotal;
    }
    
    m_totalLabel->setText(QString("总计: ¥%1").arg(m_totalAmount, 0, 'f', 2));
}

void CustomerCartUI::handleQuantityChanged(int value)
{
    // 这个函数目前使用lambda表达式实现，保留作为接口
    Q_UNUSED(value);
}

void CustomerCartUI::handleRemoveItem()
{
    // 这个函数目前使用lambda表达式实现，保留作为接口
}

// ============================================================================
// 重新下单功能扩展实现
// ============================================================================

ReorderResult CustomerCartUI::addItemsFromOrder(const QList<OrderItem>& items)
{
    ReorderResult result;
    result.totalItems = items.size();
    result.processTime = QDateTime::currentDateTime();
    
    if (!m_menuManager) {
        result.errorCode = ReorderErrorCode::SYSTEM_ERROR;
        result.message = "菜单管理器未初始化";
        return result;
    }
    
    if (items.isEmpty()) {
        result.isSuccess = true;
        result.errorCode = ReorderErrorCode::SUCCESS;
        result.message = "没有菜品需要添加";
        return result;
    }
    
    // 获取当前所有菜品信息用于验证
    auto allMenuItems = m_menuManager->getAllMenuItems();
    QHash<QString, MenuItem> menuItemMap;
    for (const auto& item : allMenuItems) {
        menuItemMap[item.id] = item;
    }
    
    // 逐个处理订单项
    for (const auto& orderItem : items) {
        if (!menuItemMap.contains(orderItem.menuItemId)) {
            // 菜品不存在或已下架
            result.failedItems++;
            result.unavailableItems.append(orderItem.menuItemName);
            continue;
        }
        
        const MenuItem& menuItem = menuItemMap[orderItem.menuItemId];
        
        if (menuItem.stock <= 0) {
            // 菜品缺货
            result.failedItems++;
            result.unavailableItems.append(orderItem.menuItemName);
            continue;
        }
        
        // 计算可添加的数量
        int requestedQuantity = orderItem.quantity;
        int availableQuantity = menuItem.stock;
        
        // 检查购物车中是否已有该菜品
        int currentCartQuantity = 0;
        for (const auto& cartItem : m_cartItems) {
            if (cartItem.menuItemId == orderItem.menuItemId) {
                currentCartQuantity = cartItem.quantity;
                break;
            }
        }
        
        // 计算实际可添加数量
        int maxPossibleQuantity = availableQuantity - currentCartQuantity;
        if (maxPossibleQuantity <= 0) {
            // 购物车中已达到库存上限
            result.failedItems++;
            result.insufficientItems.append(orderItem.menuItemName);
            continue;
        }
        
        int actualQuantity = qMin(requestedQuantity, maxPossibleQuantity);
        
        if (actualQuantity < requestedQuantity) {
            // 部分添加
            result.partialItems++;
            result.insufficientItems.append(orderItem.menuItemName);
            result.successItemsDetails.append(QString("%1 x %2 (部分)")
                .arg(orderItem.menuItemName).arg(actualQuantity));
        } else {
            // 完全添加
            result.successItems++;
            result.successItemsDetails.append(QString("%1 x %2")
                .arg(orderItem.menuItemName).arg(actualQuantity));
        }
        
        // 实际添加到购物车，复用现有的addItemToCart逻辑
        // 但这里我们需要直接操作m_cartItems以避免重复验证和UI更新
        bool itemExists = false;
        for (auto& cartItem : m_cartItems) {
            if (cartItem.menuItemId == orderItem.menuItemId) {
                cartItem.quantity += actualQuantity;
                cartItem.availableStock = menuItem.stock;
                cartItem.calculateSubtotal();
                itemExists = true;
                break;
            }
        }
        
        if (!itemExists) {
            CartItem newItem(orderItem.menuItemId, orderItem.menuItemName, 
                           menuItem.price, actualQuantity, menuItem.stock);
            m_cartItems.append(newItem);
        }
        
        // 累计金额
        result.totalAmount += menuItem.price * actualQuantity;
    }
    
    // 更新UI显示
    updateCartDisplay();
    calculateTotals();
    
    // 设置结果状态
    if (result.successItems > 0 || result.partialItems > 0) {
        result.isSuccess = true;
        result.errorCode = ReorderErrorCode::SUCCESS;
    } else {
        result.isSuccess = false;
        result.errorCode = ReorderErrorCode::ALL_ITEMS_UNAVAILABLE;
    }
    
    result.message = result.generateUserMessage();
    
    // 发送信号
    emit cartChanged(m_cartItems.size(), m_totalAmount);
    emit batchAddCompleted(result);
    
    return result;
}

ReorderResult CustomerCartUI::replaceCartWithOrder(const QList<OrderItem>& items)
{
    // 先清空购物车
    clearCart();
    
    // 然后添加新的菜品
    return addItemsFromOrder(items);
}
